package protocol

import (
	"errors"
	"serialnet/app"
	"serialnet/model"
	"serialnet/netty"
	"serialnet/netty/codec"
)

type MsgHandler struct {
	isRs232 bool
}

func NewMsgHandler(isRs232 bool) codec.Codec {
	return &MsgHandler{isRs232: isRs232}
}

func (u *MsgHandler) CodecName() string {
	return "msg-handler"
}

func (u *MsgHandler) HandleActive(ctx netty.ActiveContext) {
	app.RuntimeService.SetHandler(u.isRs232, ctx)
}

func (u *MsgHandler) HandleRead(ctx netty.InboundContext, nettyMsg netty.Message) {
	switch v := nettyMsg.(type) {
	case *model.MsgFrame:
		err := u.processMsg(v)
		if err != nil {
			app.Logger.Warn("msg deal err:", err)
		}
	}
}

// 应答报文的起始结束符  长度 CRC 均在编解码中处理
func (u *MsgHandler) processMsg(msg *model.MsgFrame) (err error) {
	if msg == nil {
		return errors.New("msg is nil")
	}
	return app.RuntimeService.ProcessMessage(u.isRs232, msg)
}

func (u *MsgHandler) HandleWrite(_ netty.OutboundContext, nettyMsg netty.Message) {
	var buffer []byte
	ok := false
	if buffer, ok = nettyMsg.([]byte); !ok {
		app.Logger.Error("error nettyMsg data")
	}
	app.Logger.Debug("写入报文长度:", len(buffer))
}

func (u *MsgHandler) HandleException(ctx netty.ExceptionContext, ex netty.Exception) {
	app.Logger.Error("peer exception: ", ex.Error())
	//stackBuffer := bytes.NewBuffer(nil)
	//ex.PrintStackTrace(stackBuffer)
	ctx.HandleException(ex)
}

func (u *MsgHandler) HandleInactive(ctx netty.InactiveContext, ex netty.Exception) {
	app.Logger.Warn("peer:", "->", "inactive:", ctx.Channel().RemoteAddr(), ex)
	// 连接断开了，默认处理是关闭连接
	ctx.HandleInactive(ex)
}

// 超时信息处理
func (u *MsgHandler) HandleEvent(_ netty.EventContext, event netty.Event) {
	switch event.(type) {
	case netty.ReadIdleEvent:

	case netty.WriteIdleEvent:

	default:
		app.Logger.Debug("未知超时！")
	}
}
